<template>
  <div class="login-container">
    <!-- 登录表单 -->
    <van-form @submit="onSubmit" v-if="loginStatus">
      <van-cell-group inset>
        <!-- 用户名输入框 -->
        <van-field
          v-model="userName"
          name="userName"
          label="用户名"
          placeholder="请输入用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <!-- 密码输入框 -->
        <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="请输入密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <!-- 错误信息提示 -->
      <div v-if="errorMessage" style="color: red; margin: 10px 0">
        {{ errorMessage }}
      </div>
      <!-- 登录按钮 -->
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          登录
        </van-button>
      </div>
      <div style="margin: 16px">
        <van-button round block type="success" @click="registerDialog">
          注册
        </van-button>
      </div>
    </van-form>

<!-- 注册 -->
    <van-form ref="registerForm" v-if="registrationStatus">
      <van-field
        v-model="userName"
        name="userName"
        label="用户名"
        placeholder="请输入用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="name"
        name="name"
        label="姓名"
        placeholder="请输入姓名"
        :rules="[{ required: true, message: '请填写姓名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="请输入密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
        v-model="confirmPassword"
        type="password"
        name="confirmPassword"
        label="确认密码"
        placeholder="请再次输入密码"
        :rules="[
          { required: true, message: '请确认密码' },
          { validator: validateConfirmPassword, message: '两次密码不一致' },
        ]"
      />
      <van-field
        v-model="phoneNumber"
        name="phoneNumber"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[
          { required: true, message: '请填写手机号' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' },
        ]"
      />
      <van-field
        v-model="gender"
        name="gender"
        label="性别"
        placeholder="请输入性别"
        :rules="[{ required: true, message: '请填写性别' }]"
      />
      <van-field
        v-model="email"
        name="email"
        label="邮箱"
        placeholder="请输入手机号"
        :rules="[
          { required: true, message: '请填写邮箱' },
          {
            pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
            message: '邮箱格式不正确',
          },
        ]"
      />

      <van-field name="date" label="选择单个日期">
        <template #input>
          <van-cell title="" :value="date" @click="show = true" />
          <van-calendar :show="show" @confirm="onConfirm" />
        </template>
      </van-field>
      <van-field name="uploader" label="头像上传">
        <template #input>
          <van-uploader
            :after-read="afterRead"
            v-model="fileList"
            multiple
            :max-count="1"
          />
        </template>
      </van-field>
      <van-field name="Register" label="">
        <template #input>
          <van-button round block type="success" @click="handleRegister">
          注册
        </van-button>
        </template>
      </van-field>
    </van-form>
  </div>
</template>
  
  <script>
import { ref, getCurrentInstance } from "vue";
/* eslint-disable */
import {  showSuccessToast, showFailToast,Dialog, Form, Field, Uploader, Icon } from "vant";
import { useAuthStore } from "@/stores/authStore";

export default {
  components: {
    VanDialog: Dialog,
    VanForm: Form,
    VanField: Field,
    VanUploader: Uploader,
    VanIcon: Icon,
  },
  setup(props, { emit }) {
    const { proxy } = getCurrentInstance(); // 获取当前实例
    const userName = ref("328994868411@qq.com");
    const password = ref("123456");
    const errorMessage = ref("");
    const authStore = useAuthStore();
 
    let registrationStatus=ref(false)
    let loginStatus=ref(true)
    const showDialog = ref(false);
    const confirmPassword = ref("");
    const phoneNumber = ref(null);
    const gender = ref(null);
    const avatar = ref([]);
    const registerForm = ref(null);
    const email = ref(null);
    const name = ref(null);
    const fileList = ref([
      // Uploader 根据文件后缀来判断是否为图片文件
      // 如果图片 URL 中不包含类型信息，可以添加 isImage 标记来声明
    //   {  isImage: true },
    ]);
    const date = ref("");
    const show = ref(false);
    const registerDialog=()=>{
      registrationStatus.value=true;
      loginStatus.value=false;
      
      console.log("点了注册按钮",loginStatus.value,registrationStatus.value)
}
    const formatDate = (date) => {
      return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
    };
    const onConfirm = (value) => {
      show.value = false;
      date.value = formatDate(value);
    };
    const afterRead = (file) => {
      const formData = new FormData();
      if (file.file.type.indexOf("image") !== -1) {
        // avatar.value = [{ ...file, content: URL.createObjectURL(file.file) }];
        formData.append("file", file.file);
      } else {
        showFailToast("上传头像图片只能是 JPG 格式!");  
        return
      }

      file.status = "uploading";
      file.message = "上传中...";

      proxy
        .$post("/api/files/uploadImage", formData)
        .then((res) => {
          if (res.status == "200") {
            fileList.value[0].url = res.data;
            file.status = "sucess";
            file.message = "上传成功";
          }
        })
        .catch((err) => {
          file.status = "failed";
          file.message = "上传失败";
        });
    };
    const handleRegister = () => {
        if (fileList.value.length === 0 || !fileList.value[0].url) {
            showFailToast("请上传头像"); 
         
          return;
        }
      const param = {
        userName: userName.value,
        profilePhotoUrl:fileList.value[0].url,
        pPassword: password.value,
        pName: name.value,
        pGender: gender.value,
        pCard: null,
        pEmail: email.value,
        pPhone: phoneNumber.value,
        pBirthday: date.value,
      };
      proxy.$post("/patient/addPatient", param).then((res) => {
        console.log(res);
        if(res.status=="200"){
          showSuccessToast("注册成功");
          registrationStatus.value=false;
          loginStatus.value=true;
          
        }
       
      });
    };

    const validateConfirmPassword = (val) => {
      return val === password.value || "两次密码不一致";
    };

    const onSubmit = (values) => {
      // 这里可以替换为实际的API请求
      proxy
        .$post("/login/loginSystem", {
          userName: userName.value,
          password: password.value,
        })
        .then((res) => {
        
          authStore.login(res.data);

          if (res.status != "200") {
            // Toast.fail('登录失败');
            showFailToast("登录失败");
            errorMessage.value="登录失败"
          } else {
            showSuccessToast("登录成功");
            //  Toast.success('登录成功');
            emit("login-success");
            console.log("点击了登陆按钮");
          }
        });
    };

    return {
      userName,
      password,
      errorMessage,
      onSubmit,
      registerDialog,
      showDialog,
      password,
      confirmPassword,
      phoneNumber,
      avatar,
      registerForm,
      handleRegister,
      validateConfirmPassword,
      fileList,
      gender,
      afterRead,
      email,
      name,
      date,
      show,
      onConfirm,
      registrationStatus,
      loginStatus
    };
  },
};
</script>
  
  <style scoped>
.login-container {
  padding: 16px;
}
</style>